package de.hwrberlin.remo.export.prolog;

import java.net.URL;

import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;

import de.hwrberlin.remo.export.xpand.XpandExporter;
import de.hwrberlin.remo.model.KnowledgeBase;

public class TemplatePrologExporter extends XpandExporter {

	private static final String BUNDLE_ID      = "de.hwrberlin.remo.export.prolog";
	private static final String GENERATOR_PATH = "/src/de/hwrberlin/remo/export/prolog/workflow/generator.mwe";

	private static final String CASE_TEMPLATE_PATH = 
		"de::hwrberlin::remo::export::prolog::templates::CaseTemplate::ExportCase";
	
	private static final String KNOWLEDGE_BASE_TEMPLATE_PATH = 
		"de::hwrberlin::remo::export::prolog::templates::KnowledgeBaseTemplate::ExportKnowledgeBase";
	
	@Override
	public void exportKnowledgeBase(String modelFilePath, KnowledgeBase base) {
		Bundle thisBundle = Platform.getBundle(BUNDLE_ID);
		URL url = thisBundle.getEntry(GENERATOR_PATH);
		
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		PrologExportDialog prologExportDialog = new PrologExportDialog(shell);

		// Open export dialog
		if(prologExportDialog.open() == Dialog.OK) {
			
			// Should export knowledge base?
			if(prologExportDialog.isExportKnowledgeBase()) {
				String knowledgeBaseFile = prologExportDialog.getKnowledgeBaseFile();
				String outputFolderPath = getFolderPath(knowledgeBaseFile);
				String fileName = getFileName(knowledgeBaseFile);
				
				// Add to parameter to template path
				String templatePath = KNOWLEDGE_BASE_TEMPLATE_PATH + "('" + fileName + "')";

				exportModel(url, templatePath, modelFilePath, outputFolderPath);
			}
			
			// Should export facts / case?
			if(prologExportDialog.isExportFacts()) {
				String factFile = prologExportDialog.getFactFile();
				String caseName = prologExportDialog.getCaseName().toLowerCase();
				String outputFolderPath = getFolderPath(factFile);
				String fileName = getFileName(factFile);
				
				// Add to parameter to template path
				String templatePath = CASE_TEMPLATE_PATH;
				templatePath += "('" + fileName + "','" + caseName + "')";
				
				exportModel(url, templatePath, modelFilePath, outputFolderPath);
			}
		}
	}
}
